package main.java.com.lee.pool;

import java.util.List;
import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2021/12/7
 */
public class PoolTest01 {
	public static void main(String[] args) {
//		singleThreadPool();
//		fixedThreadPool();
//		cachedThreadPool();
		scheduledSingleThreadPool();
//		scheduledThreadPool();
	}


	/**
	 * 单线程池
	 */
	private static void singleThreadPool() {
		ExecutorService executorService = Executors.newSingleThreadExecutor();
		IntStream.rangeClosed(1, 100).forEach(i -> {
			executorService.execute(() -> {
				System.out.println(i);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
		});
//		executorService.shutdown();
		List<Runnable> runnables = executorService.shutdownNow();

	}

	private static void fixedThreadPool() {
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		IntStream.rangeClosed(1, 100).forEach(i -> {
			executorService.execute(() -> {
				System.out.println(Thread.currentThread().getName() + "___________" + i);
			});
		});
	}

	private static void cachedThreadPool() {
		ExecutorService executorService = Executors.newCachedThreadPool();
		IntStream.rangeClosed(1, 100).forEach(i -> {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			executorService.execute(() -> {
				System.out.println(Thread.currentThread().getName() + "___________" + i);
			});
		});
		executorService.shutdown();
	}

	private static void scheduledSingleThreadPool() {
		ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
		IntStream.rangeClosed(1, 100).forEach(i -> {
			executorService.scheduleAtFixedRate(() -> {
				System.out.println(Thread.currentThread().getName() + "___________" + i);

			}, 0, 10000, TimeUnit.MILLISECONDS);
		});
//		executorService.shutdown();
	}


	private static void scheduledThreadPool() {
		ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);
		IntStream.rangeClosed(1, 100).forEach(i -> {
			executorService.scheduleAtFixedRate(() -> {
				System.out.println(Thread.currentThread().getName() + "___________" + i);

			}, 0, 10000, TimeUnit.MILLISECONDS);
		});
	}


}
